package org.gbif.agi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.appfuse.service.GenericManager;
import org.gbif.agi.model.RemoteId;
import org.appfuse.webapp.action.BaseAction;

import java.util.List;

public class RemoteIdAction extends BaseAction implements Preparable {
    private GenericManager<RemoteId, Long> remoteIdManager;
    private List remoteIds;
    private RemoteId remoteId;
    private Long  id;

    public void setRemoteIdManager(GenericManager<RemoteId, Long> remoteIdManager) {
        this.remoteIdManager = remoteIdManager;
    }

    public List getRemoteIds() {
        return remoteIds;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String remoteIdId = getRequest().getParameter("remoteId.id");
            if (remoteIdId != null && !remoteIdId.equals("")) {
                remoteId = remoteIdManager.get(new Long(remoteIdId));
            }
        }
    }

    public String list() {
        remoteIds = remoteIdManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public RemoteId getRemoteId() {
        return remoteId;
    }

    public void setRemoteId(RemoteId remoteId) {
        this.remoteId = remoteId;
    }

    public String delete() {
        remoteIdManager.remove(remoteId.getId());
        saveMessage(getText("remoteId.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            remoteId = remoteIdManager.get(id);
        } else {
            remoteId = new RemoteId();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (remoteId.getId() == null);

        remoteIdManager.save(remoteId);

        String key = (isNew) ? "remoteId.added" : "remoteId.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}